# -*- coding: utf-8 -*-
"""
Module Description: 服务器初始化
Date: 2017/12/22
Author:Bai Jin Ping
"""
import os

# from pyshare.utils.traceback_utils import print_exc
# from common import service_config
# from pyshare.framework import runtime_logger
# from pyshare.framework.async_utils.async_pool import async_pool
# from pyshare.framework.firefly_dc.globalobject import GlobalObject
# from pyshare.framework.zkutil import base_zk_node
# from pyshare.framework.amqp import Publisher

#
# def try_stop_server(try_num=0):
#     """
#     关闭服务器
#     :param try_num: 已尝试关闭次数
#     """
#     if GlobalObject.is_handlering_stop_signal:
#         return
#
#     GlobalObject.is_handlering_stop_signal = True
#
#     if try_num > 1:
#         time.sleep(0.5)
#
#     from pyshare.framework.router.runtime_request_counter import RuntimeRequestCounter
#
#     # 阻止新请求进入
#     GlobalObject.server_stop()
#
#     if RuntimeRequestCounter.processing_request_count:
#         return async_pool.submit(try_stop_server, try_num + 1)
#
#     _do_when_stop_server()
#
#     # 直接关闭进程
#     exit(0)
#
#
# def _do_when_stop_server():
#     """
#     服务进程关闭前的处理
#     """
#     # 业务进程注册的关闭逻辑
#     if GlobalObject.stophandler:
#         GlobalObject.stophandler()
#
#     # 底层框架相关的关闭处理
#     try:
#         async_pool.stop()
#     except Exception as e:
#         print_exc(e)
#
#     try:
#         from pyshare.framework.redisutils import redis_storage
#         redis_storage.RedisStorage.close_all()
#     except Exception as e:
#         print_exc(e)
#
#     try:
#         from pyshare.framework.dal.models import close_database_pool, close_profile_pool
#         close_database_pool()
#         close_profile_pool()
#     except Exception as e:
#         print_exc(e)
#
#     try:
#         base_zk_node.close_zk_client()
#     except Exception as e:
#         print_exc(e)
#
#     try:
#         if service_config.ActionLogProxyMode.is_flume_mode():
#             from pyshare.utils.game_log.log_utils import LogManager
#             LogManager.stop()
#     except Exception as e:
#         print_exc(e)
#
#
from framework.async_utils.async_pool import async_pool
from utils.traceback_utils import print_exc


def configure_server(application, config):
    """
    配置服务器(加载相关文件)
    :param application: wsgi应用对象
    :param config:
    :param server_type: 服务器类型
    """

    GlobalObject.global_config = config
    # GlobalObject.webport = config['servers']['webport']
    # 绑定wsgi app
    GlobalObject.webapp = application

    # if service_config.config['connect_zookeeper']:
    #     # zk客户端初始化
    #     from common.zk_config import zk_init, ServiceConfig
    #     zk_init()
    #
    #     # 如果处于集群模式下,则从zk获取配置值
    #     if service_config.ServerRunMode.is_cluster_mode():
    #         runtime_logger.info('集群模式启动:使用zookeeper节点更新service.json配置值')
    #
    #         zk_service_config = ServiceConfig.get_config_data()
    #         service_config.update_by_zk_service_config(zk_service_config, doing_bootstrap=True)

    # 初始化日志
    runtime_logger.init_logger()

    # 将redis初始化提前
    # 初始化redis连接
    from framework.redisutils import redis_storage
    redis_storage.RedisStorage.init(force_init_conn=True)

    # 初始化数据库代理
    from framework.dal.models import _db_pool, _db_profile_pool, \
        get_peewee_database, get_profile_database
    _db_pool.initialize(get_peewee_database())
    _db_profile_pool.initialize(get_profile_database())

    # 加载配置表到内存
    try:
        from framework.dal.gameconfig.mem_profile import MemProfileManager
        MemProfileManager.init()

    except Exception as e:
        print_exc(e)
        raise RuntimeError('配置加载异常')
    finally:
        from framework.dal.models import close_profile_pool
        close_profile_pool()

    # 确认全局配置无误
    from framework.dal.gameconfig.game_env import GameConfigEnv
    try:
        GameConfigEnv()

    except Exception as e:
        print_exc(e)
        raise RuntimeError('全局配置加载异常')

    # 开发时打印sql输出
    # 在加载完内存配置后才打印sql输出
    # from common.server_config import is_debug
    # if is_debug:
    #     from framework.dal import peewee_log
    #     peewee_log.start_logging()

    # 初始化chaos连接
    # if service_config.DalMode.is_chaos_mode()\
    #         and 'chaos_dal' in service_config.config['remoteservices']:
    #     from remote_api import set_db, set_trace, Strategy
    #     from pyshare.core.context import get_trace_id
    #     from pyshare.framework.zkutil.base_zk_node import zk_auth
    #     from pyshare.framework.dal.datasource import datasource_context_storage
    #
    #     chaos_dal_cfg = service_config.config['remoteservices']['chaos_dal']
    #
    #     set_db(
    #         datasource_context_storage.get_db_name_for_chaos,
    #         zk_host=chaos_dal_cfg['zk_host'],
    #         zk_path=chaos_dal_cfg['zk_path'],
    #         zk_user=zk_auth.split(':')[0],
    #         zk_psw=zk_auth.split(':')[1],
    #         method=chaos_dal_cfg['method'],
    #         select_node_type=Strategy.RoundRobin
    #     )
    #     set_trace(get_trace_id)

    # 初始化dal.orm
    # from pyshare.framework.dal.orm import set_db_func
    # from pyshare.framework.dal.datasource import datasource_context_storage
    # set_db_func(
    #     datasource_context_storage.get_db_name_for_chaos,
    # )
    #
    # 初始化requests Session
    from framework.http_client.client import ClientSessionConn
    ClientSessionConn.init()

    # 启动工作线程池
    async_pool.start()

    # 加载拦截器链
    from framework.interceptor.interceptor_chain import build_interceptor_chain
    build_interceptor_chain()

    # 加载消息队列
    # if service_config.config['service_switch'].get('amqp_enable', False):
    #     Publisher.init()

    # 加载应用接口
    import app.server_area

    # 初始化业务日志代理
    # from pyshare.framework.logproxy.log_proxy import GameLogProxy
    # GameLogProxy.init()
    # from pyshare.framework.logproxy.non_core_log_proxy import NonCoreLogProxy
    # NonCoreLogProxy.init()
    #
    # # 加载信号处理
    # _register_signal_term_handler()
#
#
# def _register_signal_term_handler():
#     """注册SIGTERM,SIGINT信号处理"""
#     def _handler(*args):
#         runtime_logger.info('run signal handler...' + str(args))
#
#         # gevent下处理信号的是主协程,不允许有阻塞调用
#         # 将关闭的函数放到另一个协程中,避免报BlockingSwitchOutError
#         async_pool.submit(try_stop_server)
#
#     signal.signal(signal.SIGTERM, _handler)
#     signal.signal(signal.SIGINT, _handler)
#
#
# def init_server():
#     """
#     :return boolean 是否初始化成功
#     """
#     try:
#         print 'check zookeeper connection'
#         if not base_zk_node.check_zookeeper_connectivity():
#             print 'zookeeper connection time out!'
#             return False
#
#     except Exception as e:
#         from pyshare.utils.traceback_utils import print_exc
#         print_exc(e)
#         print e.__str__()
#         return False
#
#     return True
from framework.firefly_dc import runtime_logger
from framework.firefly_dc.globalobject import GlobalObject


def start():
    """启动服务器"""
    runtime_logger.info('GameServer Start.')
    runtime_logger.info('GameServer pid: %s' % (os.getpid()))

    # 设置服务器启动状态
    GlobalObject.server_start()
